<template>
  <div>
    <el-dialog title="新增部门" :visible.sync="isShow" width="50%">
      <el-form ref="form" label-width="120px" :model="form" :rules="rules">
        <el-form-item label="部门名称" prop="name">
          <el-input v-model="form.name" />
        </el-form-item>
        <el-form-item
          label="部门编码"
          prop="code"
        ><el-input
          v-model="form.code"
        /></el-form-item>
        <el-form-item label="部门负责人" prop="manager">
          <el-select v-model="form.manager" @focus="focusEvent">
            <el-option
              v-for="item in userList"
              :key="item.id"
              :label="item.username"
              :value="item.username"
            />
          </el-select>
        </el-form-item>
        <el-form-item
          label="部门介绍"
          prop="introduce"
        ><el-input
          v-model="form.introduce"
        /></el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="isShow = false">取 消</el-button>
        <el-button type="primary" @click="isShow = false">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { sysUserSimple } from '@/api//departments'
export default {
  props: ['initData'],
  data() {
    return {
      isShow: false,
      userList: [],
      form: {
        name: '',
        code: '',
        manager: '',
        introduce: '',
        pid: ''
      },
      rules: {
        name: [
          {
            required: true,
            message: '必填',
            trigger: 'change'
          },
          {
            validator: (rules, value, callback) => {
              const resultArr = this.initData.filter((item) => {
                return item.pid === this.form.pid
              })
              console.log(resultArr)
              const resultBol = resultArr.some((item) => {
                return item.name === value
              })
              resultBol
                ? callback(new Error(`你输入了重复的部门名称:${value}`))
                : callback()
            }
          }
        ],
        code: [
          {
            required: true,
            message: '必填',
            trigger: 'change'
          }
        ],
        manager: [
          {
            required: true,
            message: '必填',
            trigger: 'change'
          }
        ],
        introduce: [
          {
            required: true,
            message: '必填',
            trigger: 'change'
          }
        ]
      }
    }
  },
  mounted() {
    this.$bus.$on('add', (bol, item) => {
      this.isShow = bol
      this.form.pid = item.id
    })
  },
  beforeDestroy() {
    this.$bus.$off('add')
  },
  methods: {
    async focusEvent() {
      if (this.userList.length === 0) {
        const res = await sysUserSimple()
        this.userList = res.data
        console.log(res)
      }
    }
  }
}
</script>

<style></style>
